#include "tools.hpp"

struct Info {
    std::string docno;
    std::string url;
    std::string title;
    std::string content;
    std::streampos pos;
    std::streamoff size;
    void reset() {
        docno.clear();
        url.clear();
        title.clear();
        content.clear();
        pos = 0;
        size = 0;
    }
};

class Handle {
private:
    int tgtxt_idx_;
    std::ofstream ofp_;
    std::string tgtxt_dir_;
private:
    bool open_file(const std::string &filename="") {
        if (!filename.empty()) {
            ofp_.open(filename, std::ios::app);
            return ofp_.is_open();
        } else {
            ++tgtxt_idx_;
            auto file = Tools::path_join(tgtxt_dir_, Tools::any2str<int>(tgtxt_idx_)+".tgtxt");
            ofp_.open(file, std::ios::app);
            return ofp_.is_open();
        }
    }
    void close_file() {
        ofp_.close();
    }
    bool is_open() {
        return ofp_.is_open();
    }
public:
    Handle(const std::string &tgtxt_dir)
            : tgtxt_idx_(0) {
        tgtxt_dir_ = tgtxt_dir;
        {
            int i_file_name = 0;
            auto tgtxts = Tools::list_file(tgtxt_dir_, ".tgtxt");
            for (auto f=tgtxts->begin(); f!=tgtxts->end(); ++f) {
                i_file_name = Tools::str2any<int>(Tools::path_file_name(*f));
                if (i_file_name >= tgtxt_idx_) {
                    tgtxt_idx_ = i_file_name;
                }
            }
        }
        this->open_file();
    }
    ~Handle() {
        if (this->is_open()) this->close_file();
    }
    void start(const std::string &db, const std::string &pwd) {

    }
};

int main(int argc, char**argv) {
    std::string tgtxt_dir = "";
    std::shared_ptr<Handle> handle = std::make_shared<Handle>(tgtxt_dir);
    handle->start();

    return 0;
}